package com.teaching.teachingsupport.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.teaching.teachingsupport.common.exception.UnauthorizedException;
import com.teaching.teachingsupport.common.pojo.dataobject.User;
import com.teaching.teachingsupport.common.pojo.dto.request.UserLoginRequest;
import com.teaching.teachingsupport.mapper.UserMapper;
import com.teaching.teachingsupport.service.service2.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@RequiredArgsConstructor
public class SecurityUtils {
    
    private final UserService userService;
    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder;
    
    /**
     * 获取当前登录用户的User对象
     */
    public User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UnauthorizedException("用户未登录");
        }
        
        Object principal = authentication.getPrincipal();
        if (!(principal instanceof UserDetails)) {
            throw new UnauthorizedException("用户未登录");
        }
        
        UserDetails userDetails = (UserDetails) principal;
        return userService.findByUsername(userDetails.getUsername());
    }
    
    /**
     * 获取当前登录用户ID
     */
    public Long getCurrentUserId() {
        // 优先从request attribute中获取，因为这是JWT解析出来的
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Object id = request.getAttribute("id");
            if (id != null) {
                return Long.valueOf(id.toString());
            }
        }
        
        // 如果request中没有，则从数据库查询
        return getCurrentUser().getUserId();
    }

    /**
     * 验证用户名和密码
     * @param username 用户名
     * @param password 密码
     * @return 如果验证通过返回用户对象，否则返回null
     */
    public User validateUser(String username, String password) {
        User user = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
        );
        
        if (user != null && passwordEncoder.matches(password, user.getPasswordHash())) {
            return user;
        }
        return null;
    }

    /**
     * 验证登录请求
     * @param request 登录请求
     * @return 如果验证通过返回用户对象，否则返回null
     */
    public User validateLoginRequest(UserLoginRequest request) {
        return validateUser(request.getUsername(), request.getPassword());
    }

    /**
     * 加密密码
     * @param rawPassword 原始密码
     * @return 加密后的密码
     */
    public String encodePassword(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }

    /**
     * 验证密码是否匹配
     * @param rawPassword 原始密码
     * @param encodedPassword 加密后的密码
     * @return 是否匹配
     */
    public boolean matchesPassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }
} 